<template>
  <div id="app" class="material-send-out-detail">
    <!-- 头部导航 -->
    <van-nav-bar ref="navBarRef" left-arrow title="拼毛发货详情" @click-left="comeBack" left-text="返回">
      <template #right>
        <span @click="openScanWinFn"><van-icon name="scan" size="20" /></span>
      </template>
    </van-nav-bar>

    <div ref="detailScrollRef" class="body-scroll" style="border-bottom: 3px solid #96b327; padding-bottom: 2vh;">
      <div class="data-card" v-for="detail in sendOutData.details">
        <div style="border-bottom: 1px solid #8191c5; color: #1677FF;justify-content: space-between">
          <span style="color: #8191c5;font-size: 1.1rem; ">{{ detail.refName.split(SPLIT_XHX)[0] }}</span>
          <span style="color: #8191c5;font-size: 1rem">批次:{{ detail.refBatchNo }}</span>
        </div>
        <div v-if="detail.vatScheduleId > 0" style="justify-content: space-between">
          <span style="color: #e6a23c">颜色: {{ detail.color }}</span>
          <span style="color: #2083fd">缸号: {{ detail.vatNo }}</span>
          <span style="color: #41d249">序号: {{ detail.vatSeqNo }}</span>
        </div>
        <div style="justify-content: space-between">
          <span style="color: #671c1c">标重: {{ detail.weight }} kg</span>
          <span style="color: #770daf">净重: {{ detail.netWeight }} kg</span>
        </div>
      </div>
    </div>

    <!-- 滚动 -->
    <better-scroll class="body-scroll" :style="'height:' + packScrollHeight" :data="packageData" :total-page="1" :pulldown="false" :pullup="false">
      <van-swipe-cell v-show="packageData.length > 0" v-for="(row, rIndex) in packageData" style="padding-bottom: 0.5rem">
        <template #default>
          <div class="data-card" :class="renderClassFn(row)">
            <div style="border-bottom: 1px solid #8191c5; color: #1677FF;justify-content: space-between">
              <span style="color: #8191c5;font-size: 1.1rem; ">{{ row.materialName.split(SPLIT_XHX)[0] }}</span>
              <span style="color: #8191c5;font-size: 1rem">批次:{{ row.batchNo }}</span>
            </div>
            <div v-if="row.vatScheduleId > 0" style="justify-content: space-between">
              <span style="color: #e6a23c">颜色: {{ row.color }}</span>
              <span style="color: #2083fd">缸号: {{ row.vatNo }}</span>
              <span style="color: #41d249">序号: {{ row.vatSeqNo }}</span>
            </div>
            <div style="justify-content: space-between">
              <span v-if="row.vatScheduleId > 0" style="color: #671c1c">标重: {{ row.weight }} kg</span>
              <span v-if="row.vatScheduleId > 0" style="color: #770daf">净重: {{ row.netWeight }} kg</span>
              <van-field v-if="row.vatScheduleId == 0" :readonly="row.status != 2" label-width="20vw" label-align="right" label="标重" colon v-model="row.weight" style="width: 60vw" @input="() => cal4Detail(row)">
                <template #extra>
                  <span style="font-size: 1.1rem; color: #671c1c;line-height: 1.4rem;">kg</span>
                </template>
              </van-field>
            </div>
            <div v-if="row.vatScheduleId > 0" style="justify-content: space-between">
              <span style="color: #671c1c">标重回潮: {{ row.stdMoisture }} %</span>
              <span style="color: #770daf">实际回潮: {{ row.actualMoisture }} %</span>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square style="margin-top: 1vh;" text="删除" type="danger" @click="delPackageDataFn(row, rIndex)" />
          </div>
        </template>
      </van-swipe-cell>
      <van-empty  v-show="packageData.length == 0" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无数据" ></van-empty>
    </better-scroll>

    <!-- 底部按钮 -->
    <div ref="footBtnRef" style="display: flex;justify-content: center;align-items: center; padding: 1vh 0vw;">
      <van-button type="primary" @click="sendConfirmFn" v-permissions="'3457_4352'">确认出库</van-button>
      <van-button type="info" @click="receiveConfirmFn" v-permissions="'606_4353'">确认收货</van-button>
    </div>
  </div>
</template>

<script>
import {comeBack} from "@/utils";
import {
  delMaterialPackageFromRef, loadMaterialPackageByVatScheduleData,
  loadMaterialPackageByRefData,
  loadMaterialPackageDetail,
  loadSendOutDetailData,
  materialReceiveConfirm,
  materialSendOutConfirm
} from "@/api/material";
import {loadFeedUsageDetail} from "@/api/feed";
import {SPLIT_COLON, SPLIT_XHX} from "@/api/enum";

export default {
  name: "materialSendOutDetail",
  data() {
    return {
      SPLIT_XHX,
      /* 查询相关 */
      queryParam: {
        keyLike: "",
        pageNum: 1,
        pageSize: 10,
        sendOutId: ""
      },

      /* 拼毛发货单 */
      sendOutData: {
        details: [],
      },
      packageData: [],
      packScrollHeight: "40vh",
      receiveFlag: false,
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    comeBack,

    /* 初始化 */
    initFn() {
      const that = this;
      //加载发货单详情
      loadSendOutDetailData(window.api.pageParam.id, data => {
        that.sendOutData = data;
        that.sendOutData.details.forEach(detail => {
          detail.weight = 0;
          detail.netWeight = 0;
        });
        //加载已发货包
        that.loadMaterialPackageDataFn();

        that.$nextTick(() => {
          //计算滚动高度
          that.packScrollHeight = window.screen.height - that.$refs.navBarRef.$el.clientHeight - that.$refs.footBtnRef.clientHeight - that.$refs.detailScrollRef.clientHeight + "px";
        });
      });
    },

    /* 打开扫码窗 */
    openScanWinFn() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          if(ret.result.indexOf("25,") == 0) {    //原料包
            loadMaterialPackageDetail(ret.result.substring(3), data => {
              //检验包是否是发货单内的
              if(!that.sendOutData.details.filter(detail => detail.type == 4).some(detail => detail.vatScheduleId == data.vatScheduleId)) {
                that.$toast("该缸散染原料不是本次发货的,请注意");
                return;
              }
              if(data.status != 2) {
                that.$toast({
                  type: "fail",
                  message: "包状态不为入库",
                  onClose: () => {
                    that.openScanWinFn();
                  }
                });
              } else if(that.packageData.findIndex(pack => pack.id == data.id) >= 0) { todo
                that.$toast({
                  type: "fail",
                  message: "包已在列表中",
                  onClose: () => {
                    that.openScanWinFn();
                  }
                });
              } else {
                that.packageData.push(data);
                that.cal4Detail(data);
                that.$toast({
                  type: "success",
                  message: "扫入成功,请继续",
                  onClose: () => {
                    that.openScanWinFn();
                  }
                });
              }
            });
          } else if(ret.result.indexOf("22,") == 0) {    //用料
            loadFeedUsageDetail(ret.result.substring(3), data => {
              //检验原料是否是发货单内的
              let detail = that.sendOutData.details.filter(detail => detail.type == 1).find(detail => detail.refId == data.refId);
              if(!detail) {
                that.$toast("该原料不是本次发货的,请注意");
                return;
              }
              let pack = {
                refId: 0,
                usageIds: data.type + SPLIT_COLON + data.id,    //用量 这里单个
                materialId: data.refId,
                materialName: data.refName,
                batchId: data.refBatchId,
                batchNo: data.refLotNo,
                weight: detail.weight,
                vatScheduleId: 0,
                status: 2,
              };
              that.packageData.push(pack);
              that.cal4Detail(pack);
            });
          } else if(ret.result.indexOf("23,") == 0) {    //按排缸
            loadMaterialPackageByVatScheduleData({vatScheduleId: ret.result.substring(3)}, data => {
              data.filter(pack => pack.status == 2).filter(pack => !that.packageData.some(p => p.id == pack.id)).forEach(pack => {
                that.packageData.push(pack);
                that.cal4Detail(pack);
              });
            });
          } else {
            that.$toast.fail("不支持的二维码")
          }
        }
      });
    },

    /* 发货确认 */
    sendConfirmFn() {
      const that = this;
      let packageData = that.packageData.filter(pack => pack.refId == 0);
      if(packageData.length == 0) {
        that.$toast.fail("没有需要处理的包")
        return;
      }
      let params = {
        planId: that.sendOutData.planId,
        planNo: that.sendOutData.yarnNo,
        refId: that.sendOutData.id,
        packs: packageData
      };
      materialSendOutConfirm(params, () => {
        that.$toast.success("发货成功");
        that.loadMaterialPackageDataFn();
      });
    },

    /* 删除包 */
    delPackageDataFn(row, index) {
      const that = this;
      if(row.refId > 0) {
        //解绑删除包
        delMaterialPackageFromRef({packageId: row.id}, () => {
          that.$toast.success("解绑(发货)成功");
          that.packageData.splice(index, 1);
          that.cal4Detail(row, true);
        });
      } else {
        that.packageData.splice(index, 1);
        that.cal4Detail(row, true);
      }
    },

    /* 加载包列表 */
    loadMaterialPackageDataFn() {
      const that = this;
      that.packageData.splice(0, that.packageData.length);
      loadMaterialPackageByRefData({
        refType: "1",
        refId: that.sendOutData.id
      }, data => {
        data.forEach(pack => {
          that.packageData.push(pack);
          that.cal4Detail(pack);
        });
      });
    },

    /* 收货确认 */
    receiveConfirmFn() {
      const that = this;
      materialReceiveConfirm({sendOutId: that.sendOutData.id}, () => {
        that.$toast.success("确认成功");
        that.loadMaterialPackageDataFn();
      });
    },

    /* 渲染 */
    renderClassFn(row) {
      if(row.status == 2) {
        return "status-in";
      } else if(row.status == 3) {
        return "status-out";
      } else {
        return "";
      }
    },

    /* 计算发货详情重量 */
    cal4Detail(pack, subtractFlag) {
      const that = this;
      if(pack.vatScheduleId > 0) {    //根据排缸匹配
        let detail = that.sendOutData.details.find(detail => detail.vatScheduleId == pack.vatScheduleId);
        if(!detail) {
          that.$toast.fail("当前包不在发货单内");
        } else {
          if(!subtractFlag) {
            detail.weight = (Number(detail.weight) + Number(pack.weight)).toFixed(2);
            detail.netWeight = (Number(detail.netWeight) + Number(pack.netWeight)).toFixed(2);
          } else {
            console.log(detail.weight, pack.weight);
            detail.weight = (Number(detail.weight) - Number(pack.weight)).toFixed(2);
            detail.netWeight = (Number(detail.netWeight) - Number(pack.weight)).toFixed(2);
          }
        }
      } else {    //原料根据批次ID匹配
        let detail = that.sendOutData.details.find(detail => detail.refBatchId == pack.batchId && detail.vatScheduleId == 0);
        if(!detail) {
          that.$toast.fail("当前包不在发货单内");
        } else {
          let packages = that.packageData.filter(pack => detail.refBatchId == pack.batchId && detail.vatScheduleId == 0);
          if(packages.length == 0) {
            detail.weight = 0;
            detail.netWeight = 0;
          } else if(packages.length == 1) {
            detail.weight = packages[0].weight;
            detail.netWeight = packages[0].weight;
          } else if(packages.length > 1) {
            detail.weight = packages.map(pack => Number(pack.weight)).reduce((a,b) => Number(a) + Number(b)).toFixed(2);
            detail.netWeight = detail.weight;
          }
        }
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.material-send-out-detail {
  height: 100%;
  .body-scroll {
    overflow: hidden;
    .van-swipe-cell__right {
      display: flex;
      flex-flow: column;
    }
    .data-card {
      width: 96vw;
      padding: 0.8rem;
      margin-left: 2vw;
      background-color: white;
      margin-top: 0.5rem;
      box-shadow: 0.3rem 0.5rem 0.3rem #888888;
      display: flex;
      flex-flow: column;
      div {
        display: flex;
        padding: 0.3rem 0rem;
        span {
          line-height: 1rem;
        }
        ::v-deep .van-field__label {
          font-size: 1.1rem;
          color: #671c1c
        }
        ::v-deep .van-field__control {
          font-size: 1.1rem;
          color: #671c1c;
          border-bottom: 1px solid #e6a23c;
        }

      }
    }
    .status-in {
      box-shadow: 0.3rem 0.5rem 0.3rem #c94949;
    }
    .status-out {
      box-shadow: 0.3rem 0.5rem 0.3rem #41d249;
    }
  }
}
</style>